<template>
  <div class="container-fluid" :style="`width: ${width};height: ${height}`">
    <div class="form-row">
      <div class="col-12">
        <div class="slidercaptcha card">
          <div class="card-header">
            <span>请完成安全验证!</span>
          </div>
          <div class="card-body">
            <div id="captcha"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {isVerify} from '@/api/user'
  import './slidercaptcha'

  export default {
    name: "index",
    props: {
      width: {type: String, default: '314px'},
      height: {type: String, default: '273px'},
      loadingText: {type: String, default: '正在加载中...'},
      failedText: {type: String, default: '再试一次'},
      barText: {type: String, default: '向右滑动填充拼图'},
      offset: {type: Number, default: 10},
    },
    mounted() {
      this.init()
    },
    data() {
      return {
        handler: null,
      }
    },
    methods: {
      init() {
        var captcha = sliderCaptcha({
          id: 'captcha',
          repeatIcon: 'el-icon-refresh-left reload',
          icon: 'el-icon-right',
          loadingText: this.loadingText,
          failedText: this.failedText,
          barText: this.barText,
          offset: this.offset,
          localImages: () => {
            return `SliderCaptcha/Pic${Math.round(Math.random() * 4)}.jpg`;
          },
          setSrc: () => {
            return `SliderCaptcha/Pic${Math.round(Math.random() * 4)}.jpg`;
          },
          remoteUrl: 'api/Captcha',
          verify: (arr, url,callback) => {
            isVerify(arr).then(res => {
              let flag = Boolean(res.data)
              callback(flag)
            }).catch(e => {
              callback(false)
            })
          },
          onFail: () => {
            this.$emit('error')
          },
          onSuccess: () => {  //成功事件
            this.$emit('success')
            this.handler = setTimeout(() => {
              window.clearTimeout(this.handler);
              try {
                captcha.reset();
              } catch (e) {
              }
            }, 500);
          }
        });

      }

    }
  }
</script>

<style lang="scss" scoped>
  @import "slidercaptcha.css";

  .slidercaptcha {
    margin: 0 auto;
    border-radius: 4px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.125);
    margin-top: 40px;
  }

  .slidercaptcha .card-body {
    padding: 1rem;
  }

  .slidercaptcha canvas:first-child {
    border-radius: 4px;
    border: 1px solid #e6e8eb;
  }

  .slidercaptcha.card .card-header {
    background-image: none;
    background-color: rgba(0, 0, 0, 0.03);
  }

  .refreshIcon {
    top: -54px;
    color: #CCCCCC;
  }

  .reload {

  }
</style>
